//
//  RBSearchResultVC.m
//  zhongzhenglu
//
//  Created by XL on 2022/7/12.
//

#import "RBSearchResultVC.h"
#import "RBDefine.h"
#import "UIView+RBAdd.h"
#import <Masonry.h>
#import "RBPager.h"
#import "RanTool.h"
#import "RBThemeConfig.h"
#import <UIImage+YYAdd.h>
#import "RBSearchResultResponse.h"
#import "RBNavigationBar.h"
#import "RBTextField.h"
#import "NSString+RBAdd.h"
#import <UINavigationController+FDFullscreenPopGesture.h>
#import "RBPersistence.h"
#import "RBSearchResultGoodsCell.h"
#import "RBGoodsDetailVC.h"
#import "RBSearchResultGroupCell.h"
#import "RBGroupDetailVC.h"
#import "RBSearchResultLimitCell.h"
#import "RBSecondKillDetailVC.h"
#import "RBSearchResultShopCell.h"
#import "RBShopDetailVC.h"

@interface RBSearchResultVC ()
<UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>
@property(nonatomic, strong)RBNavigationBar *navigationBar;
//@property(nonatomic, strong)UIScrollView *scrollView;
@property(nonatomic, strong)RBTextField *searchF;

@property (nonatomic, strong) UIView *topToolBar;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *dataSource;

@property (nonatomic, copy) NSString *type;
@property (nonatomic, strong) RBSearchResultResponse *response;

@end

@implementation RBSearchResultVC


#pragma mark - Lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setup];
    
    [self.listView.mj_header beginRefreshing];
}

#pragma mark - Private

- (void)setup
{
    self.fd_prefersNavigationBarHidden = YES;
    self.view.backgroundColor = UIColor.whiteColor;
    self.navigationBar.hidden = NO;
    self.topToolBar.hidden = NO;
    
    self.type = @"1";
}

- (void)fillData
{
    [self.dataSource removeAllObjects];
    [self.dataSource addObject:({
        RBGroupModel *group = RBGroupModel.new;
        group.cellModels = ({
            NSMutableArray *arrayM = NSMutableArray.array;
            arrayM;
        });
        group;
    })];
    [self appendData];
}
- (void)appendData {
    NSMutableArray *arrayM = ({
        RBGroupModel *group = self.dataSource.lastObject;
        (NSMutableArray *)group.cellModels;
    });
    for (RBSearchResultModel *model in self.response.data) {
        [arrayM addObject:({
            RBCellModel *cellModel = RBCellModel.new;
            LCWeakSelf;
            switch (self.type.integerValue) {
                case 1 : {
                    cellModel.reuseCellIdentifier = NSStringFromClass(RBSearchResultGoodsCell.class);
                    cellModel.cellSelectBlock = ^(NSIndexPath *indexPath) {
                        RBGoodsDetailVC *vc = RBGoodsDetailVC.new;
                        vc.id = model.goods_id;
                        [weakSelf.navigationController pushViewController:vc animated:YES];
                    };
                }   break;
                case 2 : {
                    cellModel.reuseCellIdentifier = NSStringFromClass(RBSearchResultGroupCell.class);
                    cellModel.cellSelectBlock = ^(NSIndexPath *indexPath) {
                        RBGroupDetailVC *vc = RBGroupDetailVC.new;
                        vc.id = model.group_id;
                        [weakSelf.navigationController pushViewController:vc animated:YES];
                    };
                }   break;
                case 3 : {
                    cellModel.reuseCellIdentifier = NSStringFromClass(RBSearchResultLimitCell.class);
                    cellModel.cellSelectBlock = ^(NSIndexPath *indexPath) {
                        RBSecondKillDetailVC *vc = RBSecondKillDetailVC.new;
                        vc.goods_id = model.seckill_id;
                        [weakSelf.navigationController pushViewController:vc animated:YES];
                    };
                }   break;
                case 4 : {
                    cellModel.reuseCellIdentifier = NSStringFromClass(RBSearchResultShopCell.class);
                    cellModel.cellSelectBlock = ^(NSIndexPath *indexPath) {
                        RBShopDetailVC *vc = RBShopDetailVC.new;
                        vc.id = model.store_id;
                        [weakSelf.navigationController pushViewController:vc animated:YES];
                    };
                }   break;
            }
            
            cellModel.cellData = model;
            cellModel;
        })];
    }
    [self.tableView reloadData];
    if(!arrayM.count)
    {
        [self.tableView showPlaceHolder:RB_EMPTY_TIP tapBlock:nil];
    }
}

#pragma mark - Network

- (NSString *)listPageKey
{
    return @"page";
}
- (NSDictionary *)listParams
{
    NSMutableDictionary *dicM = NSMutableDictionary.dictionary;
    dicM[@"keywords"] = self.searchF.text;
    if ([[RBAccountManager getUserId] length] > 0) {
        dicM[@"user_id"] = [RBAccountManager getUserId];
    }
    dicM[@"cate_id"] = self.class_id;
    dicM[@"type"] = self.type;
    return dicM;
}
- (NSString *)listRequestPath
{
    return @"api/search_result";
}
- (NSInteger)ListCurrentPage
{
    return self.response.currentPage;
}
- (BOOL)listLog
{
    return YES;
}
- (BOOL)listPost
{
    return YES;
}
- (Class)listResponseClass
{
    return RBSearchResultResponse.class;
}
- (UIScrollView *)listView
{
    return self.tableView;
}

- (void)getFirstPageData
{
    __weak typeof(self) weak_self = self;
    [self listLoadFirstPageWithDesView:self.listView showPlaceHolder:YES sucBlock:^(RBSearchResultResponse *data) {
        weak_self.response = data;
        [weak_self fillData];
    } failBlock:^(id data) {
        
    } reloadBlock:^{
        [weak_self getFirstPageData];
    }];
}

- (void)getNextPageData
{
    __weak typeof(self) weak_self = self;
    [self listLoadNextPageWithSucBlock:^(RBSearchResultResponse *data) {
        weak_self.response = data;
        [weak_self appendData];
    } failBlock:^(id data) {
        
    }];
}

#pragma mark - UITableViewDataSource & Delegate

kRBTableViewDataSourceAndDelegate(self.dataSource);

#pragma mark - Event

- (void)backBtnTapped
{
    [self.navigationController popViewControllerAnimated:NO];
}

- (void)searchEvent {
    [self.view endEditing:YES];
    
    if (self.searchF.text.rbLength) {
        [RBPersistence addShowSearchHistoryWithItem:self.searchF.text userId:[RBAccountManager getUserId] type:0];
    }
    
    if (self.block) {
        self.block(self.searchF.text);
    }
    [self.listView.mj_header beginRefreshing];
}

- (void)changeSegAtIndex: (NSInteger)index
{
    self.type = [NSString stringWithFormat:@"%zd", index + 1];
    [self getFirstPageData];
}

- (void)filterBtnTapped
{
    
}

#pragma mark - Setter

#pragma mark - Getter

- (RBNavigationBar *)navigationBar
{
    if (!_navigationBar)
    {
        self.navigationBar = ({
            RBNavigationBar *bar = RBNavigationBar.new;
            bar.needGradientView = NO;
            [self.view addSubview:bar];
            [bar mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.top.mas_equalTo(0);
                make.height.mas_equalTo(kRBStatusBarHeight + kRBNavigationBarHeight);
            }];
            [bar.naviBar addBackBtnWithWidth:50 image:[UIImage imageNamed:@"backBlack"]];
            [[bar.naviBar getBackBtn] removeAllTargets];
            [[bar.naviBar getBackBtn] rbAddTarget:self action:@selector(backBtnTapped)];
            
            UIButton *searchBtn = UIButton.new;
            [searchBtn rbSetTitle:@"搜索"];
            [searchBtn rbSetFontSize:18];
            [searchBtn rbSetTitleColor:[UIColor colorWithHexString:@"#222222"]];
            [searchBtn rbAddTarget:self action:@selector(searchEvent)];
            [bar.naviBar addSubview:searchBtn];
            [searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.bottom.right.mas_equalTo(0);
                make.width.mas_equalTo(56);
            }];
            
            UIView *searchView = UIView.new;
            [bar.naviBar addSubview:searchView];
            [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(bar.naviBar.getBackBtn.mas_right);
                make.right.mas_equalTo(searchBtn.mas_left);
                make.height.mas_equalTo(36);
                make.centerY.mas_equalTo(0);
            }];
            searchView.backgroundColor = [UIColor colorWithHexString:@"#F9F9F9"];
            [searchView rbSetCornerRadius:18];
            
            
            UIImageView *imgView = UIImageView.new;
            imgView.image = [UIImage imageNamed:@"homeSearchIcon"];
            [searchView addSubview:imgView];
            [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(14);
                make.centerY.mas_equalTo(0);
                make.width.height.mas_equalTo(16);
            }];
            
            RBTextField *textF = RBTextField.new;
            self.searchF = textF;
            textF.text = self.keyword;
            textF.delegate = self;
            [searchView addSubview:textF];
            [textF mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.bottom.mas_equalTo(0);
                make.left.mas_equalTo(imgView.mas_right).offset(8);
                make.right.mas_equalTo(-20);
            }];
            textF.placeholder = @"请输入商品名称";
            textF.font = [UIFont systemFontOfSize:12];
            textF.textColor = [RBThemeConfig textBlackColor];
            textF.keyboardType = UIKeyboardTypeWebSearch;
            
            bar;
        });
    }
    return _navigationBar;
}

- (UIView *)topToolBar
{
    if (!_topToolBar)
    {
        self.topToolBar = ({
            UIView *bar = UIView.new;
            [self.view addSubview:bar];
            [bar mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(self.navigationBar.mas_bottom).offset(0);
                make.left.right.mas_equalTo(0);
                make.height.mas_equalTo(Zoom(40));
            }];
            
//            UILabel *filterBtn = UILabel.new;
//            filterBtn.textAlignment = NSTextAlignmentCenter;
//            filterBtn.attributedText = [RanTool attributeStringMaker:^(NSMutableArray *maker) {
//                [maker addAttributeStringWithFont:[UIFont systemFontOfSize:Zoom(15)] color:[RBThemeConfig textBlackColor] string:@"筛选"];
//                [maker addAttributeStringWithImage:[UIImage imageWithColor:UIColor.clearColor] imageSize:CGSizeMake(Zoom(6), Zoom(6)) maxFont:[UIFont systemFontOfSize:Zoom(15)]];
//                [maker addAttributeStringWithImage:[UIImage imageNamed:@"searchFilter"] imageSize:CGSizeMake(Zoom(11), Zoom(11)) maxFont:[UIFont systemFontOfSize:Zoom(15)]];
//            }];
//            [filterBtn rbAddTapGesWithTarget:self action:@selector(filterBtnTapped)];
//            [bar addSubview:filterBtn];
//            [filterBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.right.top.bottom.mas_equalTo(0);
//                make.width.mas_equalTo(Zoom(68));
//            }];
            
//            UIImageView *lineImgView = UIImageView.new;
//            lineImgView.image = [UIImage imageNamed:@"searchFilterLine"];
//            [bar addSubview:lineImgView];
//            [lineImgView mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.right.mas_equalTo(filterBtn.mas_left);
//                make.centerY.mas_equalTo(0);
//                make.width.mas_equalTo(Zoom(4));
//                make.height.mas_equalTo(Zoom(25));
//            }];
            
            __weak typeof(self) weakSelf = self;
//            CGFloat headerW = kRBMainScreenWidth - Zoom(68) - Zoom(4);
            CGFloat headerW = kRBMainScreenWidth;
            RBPagerHeaderView *headerView = [RBPagerHeaderView new];
            [bar addSubview:headerView];
            [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.bottom.left.mas_equalTo(0);
                make.width.mas_equalTo(headerW);
            }];
            headerView.model = ({
                RBPagerHeaderModel *model = RBPagerHeaderModel.new;
                model.showSeperator = NO;
                model.showBottomLine = NO;
                model.titles = @[@"商品", @"拼团", @"秒杀", @"店铺"];
                model.headerAttributeTitlesForNormalState = ({
                    NSMutableArray *arrayM = NSMutableArray.array;
                    for (NSString *title in model.titles)
                    {
                        [arrayM addObject:[RanTool attributeStringMaker:^(NSMutableArray *maker) {
                            [maker addAttributeStringWithFont:[UIFont systemFontOfSize:Zoom(15)] color:[RBThemeConfig textBlackColor] string:title];
                        }]];
                    }
                    arrayM;
                });
                model.headerAttributeTitlesForSelectedState = ({
                    NSMutableArray *arrayM = NSMutableArray.array;
                    for (NSString *title in model.titles)
                    {
                        [arrayM addObject:[RanTool attributeStringMaker:^(NSMutableArray *maker) {
                            [maker addAttributeStringWithFont:[UIFont boldSystemFontOfSize:Zoom(15)] color:[RBThemeConfig textBlackColor] string:title];
                        }]];
                    }
                    arrayM;
                });
                model.buttonWidthStyle = RBPagerButtonWidthConstValue;
                model.headerButtonWidth = headerW/model.titles.count;
                model;
            });
            headerView.btnEventBlock = ^(NSInteger index, UIButton *btn) {
                [weakSelf changeSegAtIndex:index];
            };
            
            
            bar;
        });
    }
    return _topToolBar;
}

- (UITableView *)tableView
{
    if (!_tableView)
    {
        self.tableView = ({
            UITableView *view = [UITableView.alloc initWithFrame:CGRectZero style:UITableViewStylePlain];
            view.dataSource = self;
            view.delegate = self;
            view.showsVerticalScrollIndicator = NO;
            view.showsHorizontalScrollIndicator = NO;
            view.estimatedRowHeight = UITableViewAutomaticDimension;
            kRBTableViewCommentAdjust(view);
            view.separatorStyle = UITableViewCellSeparatorStyleNone;
            UIView *footView = [UIView new];
            footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, TAB_BAR_SAFE_MARGIN);
            view.tableFooterView = footView;
            view.mj_header = [RBRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(getFirstPageData)];
            view.mj_footer = [RBRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(getNextPageData)];
            [self.view addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.mas_equalTo(0);
                make.top.mas_equalTo(self.topToolBar.mas_bottom);
            }];
            view;
        });
    }
    return _tableView;
}

- (NSMutableArray *)dataSource
{
    if (!_dataSource)
    {
        self.dataSource = NSMutableArray.array;
    }
    return _dataSource;
}

@end
